﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Windows.Threading;
using Microsoft.Phone.Tasks;
using System.Windows.Media.Imaging;
using E_Surfing.SFReaderWP8.Model.Http;

namespace Game77SharedLib
{
    public partial class MokaBanner : UserControl
    {
        DispatcherTimer adTimer;
        int count;
        int adInterval = 20;
        int currAdIndex = 0;
        List<string> adImgs;
        List<string> adAddresses;

        public MokaBanner()
        {
            InitializeComponent();
        }

        private void Image_MouseLeftButtonDown_1(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (currAdIndex >= 0 && currAdIndex < adAddresses.Count)
            {
                WebBrowserTask webBrowserTask = new WebBrowserTask();
                webBrowserTask.Uri = new Uri(adAddresses[currAdIndex], UriKind.Absolute);
                webBrowserTask.Show();
            }
        }

        /// <summary>
        /// 开始接收广告
        /// </summary>
        /// <param name="adCount"></param>
        /// <param name="address"></param>
        /// <param name="interval"></param>
        public void StartAd(int adCount, List<string> address, List<string> imgs, int interval)
        {
            count = adCount;
            adAddresses = address;
            adImgs = imgs;
            adInterval = interval;
            currAdIndex = 0;
            if (address.Count != imgs.Count || adCount != imgs.Count || adCount < 1)
            {
                return;
            }
            if (adTimer == null && adCount > 1)
            {
                adTimer = new DispatcherTimer();
                adTimer.Interval = TimeSpan.FromSeconds(adInterval);
                adTimer.Tick += adTimer_Tick;
                adTimer.Start();
            }
            //显示第一条广告
            ShowImg();
        }

        private void ShowImg()
        {
            ReaderImage.GetImageFromNet((BitmapImage tempBitmapImage, string contentId) =>
            {
                this.imgAd.Source = tempBitmapImage;
            }, adImgs[currAdIndex], ReaderImage.GetImageAddressId(adImgs[currAdIndex]), false);
        }

        /// <summary>
        /// 停止广告
        /// </summary>
        public void StopAd()
        {
            if (adTimer != null)
            {
                adTimer.Stop();
                adTimer = null;
            }
        }

        void adTimer_Tick(object sender, EventArgs e)
        {
            currAdIndex++;
            if (currAdIndex >= count)
            {
                currAdIndex = 0;
            }
            ShowImg();
        }
    }
}
